package com.utils.info.util.hhy;

import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class JavaShellUtil {
    public static String ExecCommand(String command) {
        String outPut = "error";
        try {
            Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command}, null, null);
            int retCode = process.waitFor();
            if(retCode==0) {
                outPut = ExecOutput(process);
            }
        } catch (Exception e) {
            outPut = "error";
        }
        return outPut;
    }

    public static String ExecOutput(Process process) throws Exception {
        if (process == null) {
            return "";
        } else {
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            String output = "";
            while ((line = input.readLine()) != null) {
                output += line + "\n";
            }
            input.close();
            ir.close();
            if (output.length() > 0) {
                return output;
            }
        }
        return "";
    }
}
